package paper.check.word.parse;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import paper.check.word.commons.CommonsUtils;
import paper.check.word.model.WordModel;

/**
 * 
 * Description: 对word2007进行解析
 * 
 * @author qingjiquan@bubugao.com
 * @Date 2017年3月7日 下午5:23:41
 * @version 1.0
 * @since JDK 1.7
 */
public class Word2007Parse extends WordParse {

    private static Logger logger = LoggerFactory.getLogger(Word2007Parse.class);

    public WordModel parse(String path) {
        try {
            WordModel wordModel = new WordModel();
            InputStream is = new FileInputStream(path);
            XWPFDocument docx = new XWPFDocument(is);
            List<IBodyElement> bodyElements = docx.getBodyElements();
            List<String> paras = new ArrayList<String>();
            for (int i = 0; i < bodyElements.size(); i++) {
                IBodyElement bodyElement = bodyElements.get(i);
                switch (bodyElement.getElementType()) { // 判断标签的label
                    case PARAGRAPH:
                        XWPFParagraph paragraph = (XWPFParagraph) bodyElement; // 段落
                        parseParagraph(paragraph, paras);
                        break;
                    case TABLE:
                        break;
                    default:
                        break;
                }
            }
            wordModel.setParagraph(paras);
            return wordModel;
        } catch (Exception e) {
            logger.error("word文档解析处理错误", e);
        }
        return null;
    }

    public void parseParagraph(XWPFParagraph paragraph, List<String> paras) {
        String rawText = paragraph.getText();
        rawText = CommonsUtils.removeHeadBlank(rawText);
        if (rawText != null && rawText.length() > 2) {
            paras.add(rawText);
        }
    }
}
